#include "CSerialPort.h"
#include "plane.h"
#include <thread>
#include "getAmmo.h"

using namespace std;
void keyinput();
void enable_raw_mode();
void disable_raw_mode();
static unsigned char re_msg =  0x02 ;//���ڽ��ܵ�flag
char mode = 0x02;//ģʽ�л���0Ϊ��1Ϊ
void ReadSerial();
			pcl::console::TicToc tt;
float y_min_getammo,y_max_getammo;//-0.04, 0.06 
float y_min_plane,y_max_plane;
char c='1';
int fd;
fd_set fs_read;
struct termios option;
CSerialPort myserialport(fd, option, fs_read);      //�򿪴���

int main()
{

	std::thread *read_thresd = new std::thread(ReadSerial);
y_min_getammo=-0.02,y_max_getammo=0.05;//-0.045,0.025
y_min_plane=0,y_max_plane=0;
    thread task1(keyinput);
	while (true)
	{
		cout<<char(mode+0x30)<<endl;
		if (mode == 0x02)//getAmmo
		{
			SimpleOpenNIViewer getammo;
			getammo.run();
			
		}
		if(mode ==0x03)//pplane
		{
			cout<<"t";
			FindPlane plane;
			plane.plane_run();
		}
	}
}

void ReadSerial()
{
	while (1)
	{
		int n = myserialport.readFromCom_uchar(&re_msg,1);
		//if(n > 0)		
		//cout<<re_msg;
		if (re_msg == 0x01)
		{
			mode = 0x01;
		}
		else if (re_msg == 0x02)
		{
			mode = 0x02;
		}
		else if(re_msg == 0x03)
		{
			mode = 0x03;
		}
		usleep(1000);
	}
}


void enable_raw_mode()
{
    termios term;
    tcgetattr(0, &term);
    term.c_lflag &= ~(ICANON | ECHO); // Disable echo as well
    tcsetattr(0, TCSANOW, &term);
}

void disable_raw_mode()
{
    termios term;
    tcgetattr(0, &term);
    term.c_lflag |= ICANON | ECHO;
    tcsetattr(0, TCSANOW, &term);
}

void keyinput()
{
   enable_raw_mode();
    while(1)
    {
		
        usleep(10);
		c=getchar();
		if(c=='1'||c=='2'||c=='3'||c=='4')
		{	
			if(c=='2')
			{
				mode=re_msg=0x02;
			}
			else if(c=='3')
			{
				mode=re_msg=0x03;
			}
			else if(c=='4')
			{
				mode=re_msg=0x04;
			}
			else if(c=='1')
			{
				mode=re_msg=0x01;
			}
		}
		else if(c=='z') 
		{
			cout<<"\ny_min_getammo,y_max_getammo:"<<y_min_getammo<<","<<y_max_getammo<<endl;
			cout<<"y_min_plane,y_max_plane:"<<y_min_plane<<","<<y_max_plane<<endl;
			getchar();
		}
		else if(c=='q') y_min_getammo+=0.005;
		else if(c=='a') y_min_getammo-=0.005;
		else if(c=='w') y_max_getammo+=0.005;
		else if(c=='s') y_max_getammo-=0.005;
		else if(c=='o') y_min_plane+=0.005;
		else if(c=='k') y_min_plane-=0.005;
		else if(c=='p') y_max_plane+=0.005;
		else if(c=='l') y_max_plane-=0.005;
		
    }
	disable_raw_mode();
    tcflush(0, TCIFLUSH); // Clear stdin to prevent characters appearing on prompt
}
